package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.constant.HJBConstant;
import cn.huiyunche.base.service.enums.AvailableEnum;
import cn.huiyunche.base.service.framework.utils.HYCUtils;
import cn.huiyunche.base.service.framework.utils.HttpUtils;
import cn.huiyunche.base.service.interfaces.HJBService;
import cn.huiyunche.base.service.mappers.SHjbExtrainfoMapper;
import cn.huiyunche.base.service.mappers.SHjbNotifyLogMapper;
import cn.huiyunche.base.service.mappers.SHjbOrderLogMapper;
import cn.huiyunche.base.service.mappers.SHjbOrderMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.base.service.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 汇聚保业务实现
 *
 * @author hdy [Tuffy]
 */
@Service
public class HJBServiceImpl implements HJBService {

    @Autowired
    private SHjbExtrainfoMapper sHjbExtrainfoMapper = null;

    @Autowired
    private SHjbOrderMapper sHjbOrderMapper = null;

    @Autowired
    private SHjbOrderLogMapper sHjbOrderLogMapper = null;

    @Autowired
    private SHjbNotifyLogMapper sHjbNotifyLogMapper = null;

    private final String Y = "Y";

    @Override
    public Result<HJBOrderRtnVo> order(String orderCode, String productCode, String notifyUrl, HJBOrderExtraInfoFormVo hefv) throws ParseException, IOException {
        Result<HJBOrderRtnVo> r = new Result<>(false);
        // 预计起运时间
        Date startTime = hefv.getStartTime();
        if (DateUtils.daysBetween(new Date(), startTime) < 0) {
            r.setMessage("预计起运时间小于当前时间");
            return r;
        }
        // 1. 保存业务表单数据
        SHjbExtrainfo she = this.saveHjbExtrainfoOrder(orderCode, hefv);
        SHjbOrder sho = this.saveHjbOrder(productCode, notifyUrl, she);
        // 2. 提交表单数据
        SHjbOrderLog result = this.postHjbOrder(she, sho);
        if (!result.getIsSuccess().equals(Y)) {
            r.setMessage(result.getErrMsg());
            return r;
        }
        // 3. 保存日志
        this.saveSHjbOrderLog(result, sho);
        r.setSuccess(true);
        return r;
    }

    @Override
    public String notify(HJBNotifyVo hnv) {
        SHjbOrderExample soe = new SHjbOrderExample();
        soe.createCriteria().andChannelOrderNoEqualTo(hnv.getCHANNEL_ORDER_NO());
        List<SHjbOrder> list = this.sHjbOrderMapper.selectByExample(soe);
        SHjbOrder so = list.size() > 0 ? list.get(0) : null;
        if (null != so) {
            so.setNotifyTime(new Date());
            this.sHjbOrderMapper.updateByPrimaryKey(so);
        }
        this.saveHjbNotifyLog(hnv);
        return "success";
    }

    @Override
    public Result<HjbCheckOrderVo> orderStatus(String orderCode) {
        Result<HjbCheckOrderVo> r = new Result<>(true);
        HjbCheckOrderVo hcov = new HjbCheckOrderVo();
        hcov.setOrder(false);
        // 查询保单数据
        SHjbExtrainfoExample shee = new SHjbExtrainfoExample();
        shee.createCriteria().andFreightNoEqualTo(orderCode);
        List<SHjbExtrainfo> sheList = this.sHjbExtrainfoMapper.selectByExample(shee);
        SHjbExtrainfo she = sheList.size() > 0 ? sheList.get(0) : null;
        if (null != she) {
            hcov.setOrder(true);
            SHjbNotifyLogExample shnle = new SHjbNotifyLogExample();
            shnle.createCriteria().andChannelOrderNoEqualTo(she.getChannelOrderNo());
            List<SHjbNotifyLog> shnlList = this.sHjbNotifyLogMapper.selectByExample(shnle);
            if (shnlList.size() > 0) {
                hcov.setPolicy(true);
                hcov.setOrderUrl(shnlList.get(0).getDocUrl());
            } else {
                hcov.setPolicy(false);
            }
        }
        r.setData(hcov);
        return r;
    }

    /**
     * 保存回调数据
     *
     * @param hnv
     */
    private void saveHjbNotifyLog(HJBNotifyVo hnv) {
        SHjbNotifyLogExample shnle = new SHjbNotifyLogExample();
        shnle.createCriteria().andChannelOrderNoEqualTo(hnv.getCHANNEL_ORDER_NO());
        List<SHjbNotifyLog> sList = this.sHjbNotifyLogMapper.selectByExample(shnle);
        SHjbNotifyLog snl = sList.size() > 0 ? sList.get(0) : new SHjbNotifyLog();
        snl.setChannelOrderNo(hnv.getCHANNEL_ORDER_NO());
        snl.setDocUrl(hnv.getDOC_URL());
        snl.setPolicyNo(hnv.getPOLICY_NO());
        snl.setSysOrderNo(hnv.getSYS_ORDER_NO());
        if (null == snl.getId()) {
            this.sHjbNotifyLogMapper.insert(snl);
        } else {
            this.sHjbNotifyLogMapper.updateByPrimaryKey(snl);
        }
    }

    /**
     * 保存业务数据
     *
     * @param orderCode
     * @param hefv
     * @return 业务订单对喜庆
     */
    private SHjbExtrainfo saveHjbExtrainfoOrder(String orderCode, HJBOrderExtraInfoFormVo hefv) {
        SHjbExtrainfo she = new SHjbExtrainfo();
        BeanCopier beanCopierT = BeanCopier.create(HJBOrderExtraInfoFormVo.class, SHjbExtrainfo.class, false);
        beanCopierT.copy(hefv, she, null);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        she.setChannelOrderNo(uuid);
        she.setExpectStartTime(NumberUtils.toLong(DateUtils.getStringFromDate(hefv.getStartTime(), "yyyyMMddHHmmss")));
        she.setTransportType("汽运");
        she.setLoadType("非集装箱");
        she.setPackType("裸装");
        she.setGoodsType("机械设备类");
        she.setFreightNo(orderCode);
        String stopovers = she.getStopovers();
        if (StringUtils.isBlank(stopovers)) {
            she.setStopovers("");
        }
        this.sHjbExtrainfoMapper.insert(she);
        return she;
    }

    /**
     * 保存订单数据
     *
     * @param productCode
     * @param notifyUrl
     * @param she
     * @return
     */
    private SHjbOrder saveHjbOrder(String productCode, String notifyUrl, SHjbExtrainfo she) {
        SHjbOrder sho = new SHjbOrder();
        sho.setChannelOrderNo(she.getChannelOrderNo());
        sho.setExtraInfoId(she.getId());
        sho.setIsOk(AvailableEnum.F.getValue());
        sho.setProductCode(productCode);
        sho.setChannelId(HYCUtils.getConstantPropertiesLoader().getProperty(HJBConstant.HJB_CHANNEL_ID));
        sho.setNotifyUrl(notifyUrl);
        this.sHjbOrderMapper.insert(sho);
        return sho;
    }

    /**
     * 提交数据
     *
     * @param she
     * @param sho
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    private SHjbOrderLog postHjbOrder(SHjbExtrainfo she, SHjbOrder sho) throws IOException {
        HJBOrderFormVo horv = new HJBOrderFormVo();
        horv.setExtrainfo(she);
        horv.setChannelId(sho.getChannelId());
        horv.setChannelOrderNo(sho.getChannelOrderNo());
        horv.setNotifyUrl(sho.getNotifyUrl());
        horv.setProductCode(sho.getProductCode());
        // 请求地址
        return HttpUtils.hjbOrderPost(horv);
    }

    /**
     * 保存订单日志
     *
     * @param sol
     * @param sho
     */
    private void saveSHjbOrderLog(SHjbOrderLog sol, SHjbOrder sho) {
        this.sHjbOrderLogMapper.insert(sol);
        if (sol.getIsSuccess().equals(Y)) {
            sho.setIsOk(AvailableEnum.T.getValue());
            this.sHjbOrderMapper.updateByPrimaryKey(sho);
        }
    }

}
